package org.jsola.hr.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsola.approval.entity.UserApproDO;
import org.jsola.approval.service.listener.IApproUserNoticeListenerService;
import org.jsola.approval.vo.ApproNoticeModuleContext;
import org.jsola.common.DateKit8;
import org.jsola.hr.constant.ConfigCodeConstants;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.entity.CompanyDO;
import org.jsola.hr.provider.IMessageProviderService;
import org.jsola.hr.provider.INoticeProviderService;
import org.jsola.hr.provider.ISiteConfigProviderService;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.service.ICompanyService;
import org.jsola.message.dto.WeiXinDTO;
import org.jsola.message.dto.WxTemplateParam;
import org.jsola.notice.constant.NoticeConstants;
import org.jsola.notice.constant.ReceiveDateTypeEnum;
import org.jsola.notice.vo.NoticeRuleSettingVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.entity.UnionOpenIdDO;
import org.jsola.user.entity.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zxy
 * @date 2020/5/29
 */
@Slf4j
@Service("hrApproUserNoticeListenerServiceImpl")
public class ApproUserNoticeListenerServiceImpl implements IApproUserNoticeListenerService {

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IUserProviderService userProviderService;

    @Autowired
    private IMessageProviderService messageProviderService;

    @Autowired
    private ISiteConfigProviderService siteConfigProviderService;

    @Autowired
    private INoticeProviderService noticeProviderService;

    @Override
    public Boolean isSupport(String moduleType, String subjectType, String subjectId, String companyId) {
        return "hr".equals(moduleType);
    }

    @Override
    public ApproNoticeModuleContext waitApproTask(ApproNoticeModuleContext approNoticeModuleContext) {
        // 待审批任务发送微信通知
        sendWeiXinWaitTask(approNoticeModuleContext);

        return approNoticeModuleContext;
    }

    @Async
    void sendWeiXinWaitTask(ApproNoticeModuleContext approNoticeModuleContext) {
        try {
            TokenUser tokenUser = approNoticeModuleContext.getTokenUser();
            if (Objects.isNull(tokenUser)) {
                log.info("人力-审批通知审批人错误,tokenUser不存在,test:{}", approNoticeModuleContext);
                return;
            }
            // 模块
            String moduleType = approNoticeModuleContext.getModuleType();
            if (StringUtils.isEmpty(moduleType) || !"hr".equals(moduleType)) {
                log.info("人力-审批通知模块错误,模块不是人力,test:{}", approNoticeModuleContext);
                return;
            }
            // 公司id
            String companyId = approNoticeModuleContext.getCompanyId();
            if (StringUtils.isEmpty(companyId)) {
                log.info("人力-审批通知公司错误,公司id不存在,test:{}", approNoticeModuleContext);
                return;
            }
            CompanyDO company = companyService.selectDOById(companyId, tokenUser.getSiteId());
            if (Objects.isNull(company)) {
                log.info("人力-审批通知公司错误,公司id:{}对应的公司不存在,test:{},siteId:{}", companyId, approNoticeModuleContext, tokenUser.getSiteId());
                return;
            }
            // 审批发起人
            String approCreateUserId = approNoticeModuleContext.getApproCreateUserId();
            if (StringUtils.isEmpty(approCreateUserId)) {
                log.info("人力-审批通知审批发起人错误,审批发起人不存在,test:{},siteId:{}", approNoticeModuleContext, tokenUser.getSiteId());
                return;
            }
            UserDO userCreate = userProviderService.selectUserById(approCreateUserId);
            if (Objects.isNull(userCreate)) {
                log.info("人力-审批通知审批发起人错误,审批发起人id:{}对应的人员不存在,test:{},siteId:{}", approCreateUserId, approNoticeModuleContext, tokenUser.getSiteId());
                return;
            }
            // 审批任务审批人
            String taskApproverUserId = approNoticeModuleContext.getTaskApproverUserId();
            if (StringUtils.isEmpty(taskApproverUserId)) {
                log.info("人力-审批通知审批任务审批人错误,审批任务审批人不存在,test:{},siteId:{}", approNoticeModuleContext, tokenUser.getSiteId());
                return;
            }
            UserDO userTask = userProviderService.selectUserById(taskApproverUserId);
            if (Objects.isNull(userTask)) {
                log.info("人力-审批通知审批任务审批人错误,审批任务审批人id:{}对应的人员不存在,test:{},siteId:{}", taskApproverUserId, approNoticeModuleContext, tokenUser.getSiteId());
                return;
            }
            String appid = siteConfigProviderService.selectValueByCode(ConfigCodeConstants.CODE_APPID_ADMIN, tokenUser.getSiteId());
            UnionOpenIdDO unionOpenId = userProviderService.getUnionOpenByUserId(appid, taskApproverUserId);
            if (Objects.isNull(unionOpenId) || StringUtils.isEmpty(unionOpenId.getOpenId())) {
                log.info("人力-通知人unionid错误,审批任务审批人id:{}在appid:{}对应的openid不存在,test:{},siteId:{}", taskApproverUserId, appid, approNoticeModuleContext, tokenUser.getSiteId());
                return;
            }

            NoticeRuleSettingVO noticeRuleSettingVO = noticeProviderService.selectByTypeCodeAndCompany(HrConstants.HR_SUBJECT_TYPE,
                    NoticeConstants.APPROVAL, companyId);
            if (!noticeRuleSettingVO.getEnableStatus()) {
                return;
            }
            // 审批只发给下个节点处理人
            Integer receiveDateType = noticeRuleSettingVO.getReceiveDateType();
            if (ReceiveDateTypeEnum.RIGHT_NOW.getValue().equals(receiveDateType)) {

                UserApproDO userAppro = approNoticeModuleContext.getUserAppro();
                String templateId = siteConfigProviderService.selectValueByCode(ConfigCodeConstants.CODE_TODO_REMINDER_ADMIN, tokenUser.getSiteId());
                /**
                 * {{first.DATA}}
                 * 事项名称：{{keyword1.DATA}}
                 * 事项摘要：{{keyword2.DATA}}
                 * 处理人员：{{keyword3.DATA}}
                 * 时间：{{keyword4.DATA}}
                 * {{remark.DATA}}
                 */
                // 推送微信模板消息
                WeiXinDTO weiXinDTO = new WeiXinDTO();
                weiXinDTO.setAppId(appid);
                weiXinDTO.setTemplateId(templateId);
                weiXinDTO.setToUser(unionOpenId.getOpenId());
                // 参数
                List<WxTemplateParam> paramList = new ArrayList<>();
                WxTemplateParam param1 = new WxTemplateParam();
                param1.setName("first");
                param1.setValue("您好，您有未处理事项，请及时处理「" + company.getName() + "」");
                paramList.add(param1);

                WxTemplateParam param2 = new WxTemplateParam();
                param2.setName("keyword1");
                param2.setValue("业务审批");
                paramList.add(param2);

                WxTemplateParam param3 = new WxTemplateParam();
                param3.setName("keyword2");
                param3.setValue("您有一个业务待审批-" + userAppro.getRemark());
                paramList.add(param3);
                userAppro.getAllNodeIds();

                WxTemplateParam param4 = new WxTemplateParam();
                param4.setName("keyword3");
                // 审批节点名称+审批人
                UserDO userDO = userProviderService.selectUserById(taskApproverUserId);
                String name;
                if (userDO != null) {
                    name = userDO.getName();
                } else {
                    name = "系统";
                }
                param4.setValue(name);
                paramList.add(param4);

                WxTemplateParam param5 = new WxTemplateParam();
                param5.setName("keyword4");
                param5.setValue(DateKit8.getCurrentDay(DateKit8.DATE));
                paramList.add(param5);

                WxTemplateParam param6 = new WxTemplateParam();
                param6.setName("remark");
                param6.setValue("请及时处理。");
                paramList.add(param6);

                weiXinDTO.setTemplateParamList(paramList);
                messageProviderService.sendWeChatTempMessage(weiXinDTO, tokenUser);
            }
        } catch (Exception e) {
            log.info("审批微信通知待审批人任务出错");
            e.printStackTrace();
        }
    }
}
